/** @format */

// 进度条
var box = document.getElementById("box");
var progress = document.getElementById("progress");
var timer = null;
var percentage = 0;

var url = location.search.substring(1);

pdfjsLib.cMapUrl = "https://unpkg.com/pdfjs-dist@2.3.200/cmaps/";
pdfjsLib.cMapPacked = true;

var pdfDoc = null;

function createPage() {
  var div = document.createElement("canvas");
  document.body.appendChild(div);
  return div;
}

function renderPage(num) {
  pdfDoc.getPage(num).then(function (page) {
    var viewport = page.getViewport({ scale: 2.0 });
    var canvas = createPage();
    var ctx = canvas.getContext("2d");

    canvas.height = viewport.height;
    canvas.width = viewport.width;

    page.render({
      canvasContext: ctx,
      viewport: viewport,
    });
  });
}

var totalPages = 0;
var currentPages = 0;
start();
pdfjsLib.getDocument(url).promise.then(function (pdf) {
  pdfDoc = pdf;
  totalPages = pdfDoc.numPages;
  complete();
  if (totalPages < 5) {
    currentPages = totalPages;
  } else {
    currentPages = 5;
  }
  for (var i = 1; i <= currentPages; i++) {
    renderPage(i);
  }
});

// 监听body的滚动事件
window.onscroll = function () {
  var windowHeight =
    document.documentElement.clientHeight || document.body.clientHeight;
  // 页面高度
  var documentHeight =
    document.documentElement.scrollHeight || document.body.scrollHeight;
  // 滚动条位置
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  if (windowHeight + scrollTop + 150 >= documentHeight) {
    console.log("页面滚动到达底部");
    if (currentPages < totalPages) {
      const prePages = currentPages + 1;
      currentPages = currentPages + 5;
      if (currentPages > totalPages) {
        currentPages = totalPages;
      }
      for (var i = prePages; i <= currentPages; i++) {
        renderPage(i);
      }
    }
  }
};

// 开始加载
function start() {
  box.style.display = "block";
  document.body.style.overflow = "hidden";
  timer = setInterval(increaseProgress, 500);
}

function increaseProgress() {
  if (percentage < 60) {
    percentage += 5;
  } else if (percentage < 90) {
    percentage += 3;
  } else {
    percentage += 1;
  }
  progress.style.width = percentage + "%";
  if (percentage >= 98) {
    clearInterval(timer);
  }
}

// 完成加载
function complete() {
  clearInterval(timer);
  progress.style.width = "100%";
  setTimeout(function () {
    box.style.display = "none";
    document.body.style.overflow = "auto";
  }, 1000);
}
